package ws_socket

import (
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"unsafe"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func WsHandler(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println(err)
		return
	}

	defer conn.Close()
	client := Client{
		ip:   "192.168.181.128",
		user: "root",
		pwd:  "admin@123",
	}
	for {
		// 读取消息
		_, msg, err := conn.ReadMessage()
		if err != nil {
			log.Println(err)
			return
		}

		// 处理消息
		log.Printf("收到消息: %s", msg)
		if len(msg) != 0 {
			msg = StringToBytes(client.Run(string(msg)))
		} else {
			msg = StringToBytes("")
		}
		// 回复消息
		err = conn.WriteMessage(websocket.TextMessage, []byte(msg))
		if err != nil {
			log.Println(err)
			return
		}
	}
}

func StringToBytes(s string) (b []byte) {
	return *(*[]byte)(unsafe.Pointer(
		&struct {
			string
			Cap int
		}{s, len(s)},
	))
}
